'use strict';

const db = uniCloud.database();
const collection = db.collection('food-banner');

exports.main = async (event, context) => {
  const { bannerId, bannerData } = event.data || {};
  
  if (!bannerId) {
    return {
      code: 400,
      message: '轮播图ID不能为空',
      data: null
    };
  }
  
  if (!bannerData) {
    return {
      code: 400,
      message: '轮播图数据不能为空',
      data: null
    };
  }
  
  try {
    // 检查轮播图是否存在
    const existingBanner = await collection.doc(bannerId).get();
    
    if (!existingBanner.data || existingBanner.data.length === 0) {
      return {
        code: 404,
        message: '轮播图不存在',
        data: null
      };
    }
    
    // 如果更新了标题，检查标题是否重复
    if (bannerData.title && bannerData.title.trim() !== existingBanner.data[0].title) {
      const duplicateBanner = await collection.where({
        title: bannerData.title.trim(),
        _id: db.command.neq(bannerId)
      }).get();
      
      if (duplicateBanner.data.length > 0) {
        return {
          code: 400,
          message: '轮播图标题已存在',
          data: null
        };
      }
    }
    
    // 准备更新数据
    const updateData = {
      update_date: Date.now()
    };
    
    // 只更新传入的字段
    if (bannerData.title !== undefined) {
      updateData.title = bannerData.title.trim();
    }
    if (bannerData.image !== undefined) {
      updateData.image = bannerData.image;
    }
    if (bannerData.link_type !== undefined) {
      updateData.link_type = bannerData.link_type;
    }
    if (bannerData.link_value !== undefined) {
      updateData.link_value = bannerData.link_value;
    }
    if (bannerData.sort !== undefined) {
      updateData.sort = bannerData.sort;
    }
    if (bannerData.status !== undefined) {
      updateData.status = bannerData.status;
    }
    
    // 执行更新
    const result = await collection.doc(bannerId).update(updateData);
    
    if (result.updated === 1) {
      // 获取更新后的数据
      const updatedBanner = await collection.doc(bannerId).get();
      return {
        code: 200,
        message: '更新成功',
        data: updatedBanner.data[0]
      };
    } else {
      return {
        code: 500,
        message: '更新失败',
        data: null
      };
    }
  } catch (error) {
    return {
      code: 500,
      message: '更新失败: ' + error.message,
      data: null
    };
  }
};